--sht1x read

--io
local sda = 7
local scl = 8
gpio.mode(sda, gpio.INPUT)
gpio.mode(scl, gpio.OUTPUT)

local index = 1
local idx = {3, 5}
table.sort(idx)

local mytimer = tmr.create()
local readtimer = tmr.create()

-- function
local function dl()
    gpio.mode(sda, gpio.OUTPUT)
	gpio.write(sda, gpio.LOW)
end

local function dh()
    gpio.mode(sda, gpio.OUTPUT)
    gpio.write(sda, gpio.HIGH)
end

local function cl()
	gpio.write(scl, gpio.LOW)
end

local function ch()
	gpio.write(scl, gpio.HIGH)
end

-- get SDA value
local function dr()
	gpio.mode(sda, gpio.INPUT)
	return gpio.read(sda)
end

local function read_byte()
	local val = 0
	for i = 0, 7 do
		ch()
		val = val * 2 + dr()
		cl()
	end
	return val
end

local function write_byte(val)
	for i = 0, 7 do
		if bit.band(val, 2 ^ (7-i)) == 0 then
			dl()
		else
			dh()
		end
		ch() cl()
	end
end

local function read_cmd(cmd)
	dh() ch() dl() cl() ch() dh()
	cl() -- transmission start sequence
	write_byte(cmd)
	ch() cl()

    local t_wait
    if (index == 1) then
        t_wait = 320
    else
        t_wait = 80
    end

    --wait
    mytimer:alarm(t_wait, tmr.ALARM_AUTO, function (t)
        if dr() == gpio.LOW then
            t:unregister()

            dh()
            local val = read_byte()
            dh() dl() ch() cl() dh() -- ackhowledge
            val = val * 256 + read_byte()
            dh() ch() cl() -- skip crc
            --temp
            if (cmd == 3) then
                _G._t = val
            end
			--hum
            if (cmd == 5) then
                _G._rh = val
				_G._timestamp = rtctime.get()
                _G._busy = false
            end
        -- inner if
            collectgarbage()
        end
    end)
end

readtimer:alarm(10000, tmr.ALARM_AUTO, function (t)
    if (index == 1) then
        _G._busy = true
    end
    read_cmd(idx[index])
    index = index + 1
    if(index > 2) then
        index = 1
    end
end)

